package com.gcpproxy.controller;

import com.gcpproxy.api.GeminiApiClient;
import com.gcpproxy.model.*;
import com.gcpproxy.response.ResponseFormatter;
import com.google.genai.types.GenerateContentResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 聊天完成控制器
 */
@RestController
@RequestMapping("/v1")
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private GeminiApiClient geminiApiClient;

    @Autowired
    private ResponseFormatter responseFormatter;

    /**
     * Chat Completions API端点 - OpenAI兼容格式
     */
    @PostMapping("/chat/completions")
    public ResponseEntity<?> chatCompletions(@RequestBody ChatCompletionRequest request) {
        String requestId = UUID.randomUUID().toString();
        logger.info("=== 收到Chat Completions请求 - ID: {} ===", requestId);

        try {
            RequestParameters params = extractParameters(request);
            ParsedMessage parsedMessage = parseMessages(request.getMessages());
            String selectedModel = selectModel( request.getModel() , parsedMessage);
            boolean generateImage = false;
            if( selectedModel.contains( "flash-image" )) {
                generateImage = true ;
            }
            List<String> responseModalities = determineResponseModalities(parsedMessage,  generateImage );
            
            logger.info("使用模型: {}, 响应模态: {}", selectedModel, responseModalities);

            return generateResponse(selectedModel, parsedMessage,  responseModalities, requestId, request);

        } catch (Exception e) {
            logger.error("Chat completions error: {}", e.getMessage(), e);
            return ResponseEntity.status(500)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(ErrorResponse.create(
                    "服务器内部错误: " + e.getMessage(),
                    "server_error",
                    "internal_error"
                ));
        }
    }

    private RequestParameters extractParameters(ChatCompletionRequest request) {
        RequestParameters params = new RequestParameters();
        params.setModel(request.getModel());
        params.setTemperature(request.getTemperatureOrDefault());
        params.setMaxTokens(request.getMaxTokensOrDefault());
        params.setStream(request.isStreamOrDefault());
        if( request.getModel().contains( "flash-image" )) {
            params.setGenerateImage( true );
        }else{
            params.setGenerateImage( false );
        }
        return params;
    }

    private String selectModel(String model, ParsedMessage parsedMessage) {
        if (model != null && !model.trim().isEmpty()) {
            return model;
        }
        
        if (parsedMessage.hasImages()) {
            logger.info("model 为 null 且检测到图片参数，使用 gemini-2.5-flash-image");
            return "gemini-2.5-flash-image";
        } else {
            logger.info("model 为 null 且无图片参数，使用 gemini-2.5-pro");
            return "gemini-2.5-pro";
        }
    }

    private ParsedMessage parseMessages(List<ChatMessage> messages) {
        ParsedMessage parsed = new ParsedMessage();
        
        for (ChatMessage message : messages) {
            parsed.setTextPrompt(parsed.getTextPrompt() + message.getTextContent());
            parsed.getImages().addAll(message.getImageUrls());
        }

        logger.info("解析结果 - 文本长度: {}, 图片数量: {}", parsed.getTextPrompt().length(), parsed.getImages().size());
        return parsed;
    }

    private List<String> determineResponseModalities(ParsedMessage parsedMessage, boolean generateImage) {
        if (generateImage) {
            logger.info("设置响应模态为: [ 'image']");
            return Arrays.asList( "image");
        } else {
            logger.info("设置响应模态为: ['text']");
            return Arrays.asList("text");
        }
    }

    private ResponseEntity<?> generateResponse(
            String selectedModel, ParsedMessage parsedMessage,  List<String> responseModalities,
            String requestId, ChatCompletionRequest originalRequest) {
        logger.info("开始调用API生成响应...");

        GenerateContentResponse apiResponse = geminiApiClient.generateContent(
            selectedModel,
            parsedMessage.getTextPrompt(),
            parsedMessage.getImages(),
            responseModalities,
            originalRequest.getTemperatureOrDefault(),
            originalRequest.getMaxTokensOrDefault()
        );

        GeminiResponse formattedResponse = responseFormatter.formatChatCompletionResponse(
            apiResponse, selectedModel, requestId, originalRequest
        );
        
        logger.info("=== Chat Completions请求处理完成 - ID: {} ===", requestId);
        return ResponseEntity.ok(formattedResponse);
    }
}